package com.sanjin.listener;

import com.aliyun.openservices.ons.api.*;
import com.sanjin.entity.ParkSpace;
import com.sanjin.service.ParkSpaceService;
import lombok.extern.log4j.Log4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.Properties;


/**
 * @description: 监听 SpringBoot 启动，监听物联网MQ消息队列的消息
 * @author: sanjin
 * @date: 2019/5/15 16:48
 */
@Component
@Log4j
public class LoadLotMQListener implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private ParkSpaceService parkSpaceService;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        // 加载MQ消息队列的监听
        Properties properties = new Properties();
        // 您在控制台创建的 Group ID
        properties.put(PropertyKeyConst.GROUP_ID, "GID_radardata");
        // AccessKey 阿里云身份验证，在阿里云服务器管理控制台创建
        properties.put(PropertyKeyConst.AccessKey, "LTAIHmEKgbqe1WMU");
        // SecretKey 阿里云身份验证，在阿里云服务器管理控制台创建
        properties.put(PropertyKeyConst.SecretKey, "09cNYfAsTxvaqBXwWzBiASUjojls4c");
        // 设置 TCP 接入域名，到控制台的实例基本信息中查看
        properties.put(PropertyKeyConst.NAMESRV_ADDR,
                "http://MQ_INST_1756844100799746_BbAQtnlc.mq-internet-access.mq-internet.aliyuncs.com:80");
        // 集群订阅方式 (默认)
        // properties.put(PropertyKeyConst.MessageModel, PropertyValueConst.CLUSTERING);
        // 广播订阅方式
        // properties.put(PropertyKeyConst.MessageModel, PropertyValueConst.BROADCASTING);
        Consumer consumer = ONSFactory.createConsumer(properties);
        consumer.subscribe("radardata", "*", new MessageListener() { //订阅全部 Tag
            public Action consume(Message message, ConsumeContext context) {
                String messageBody = new String(message.getBody());
                log.info("【Receive MQ 消息】: " + messageBody);
                handleMQMessage(messageBody);
                return Action.CommitMessage;
            }
        });
        consumer.start();
        log.info("【监听物联网MQ组件加载成功...】");
    }

    /**
     * 处理MQ消息
     */
    private void handleMQMessage(String message) {
        /*JSON字符串处理*/
        JSONObject jsonObject = JSONObject.fromObject(message);
        int mtype_int = jsonObject.getInt("mtype");
        if(mtype_int==0){
            System.out.println("join请求，不计入数据库");
            return;
        }
        else if (mtype_int==4){
            System.out.println("confirmed up 计入数据库");
        }
        String data_str = jsonObject.getString("data"), // 车进入离开数据
                datr_str = jsonObject.getString("datr"),
                devAddr_str = jsonObject.getString("devAddr"),
                devEui_str = jsonObject.getString("devEui"),
                fcnt_str = jsonObject.getString("fcnt"),
                fport_str = jsonObject.getString("fport"),
                gwEui_str = jsonObject.getString("gwEui"),
                joinEui_str = jsonObject.getString("joinEui"),
                mtype_str = jsonObject.getString("mtype"),
                rssi_str = jsonObject.getString("rssi"),
                snr_str = jsonObject.getString("snr"),
                time_str = jsonObject.getString("time");
        if (Integer.parseInt(data_str, 16) == 110) {
            // 110 表示 n 有车离开停车位
//            String mockLoraAddr = "d896e0fff0102893";
            String mockLoraAddr = devEui_str;
            ParkSpace parkSpace = parkSpaceService.queryParkSpaceByLoraAddr(mockLoraAddr);
            log.info("【修改车位状态】：车位lora地址:"+parkSpace.getLoraAddr()+",车位id："+parkSpace.getId());
            // 设置车位状态位 0 -> 空闲
            parkSpace.setStatus(0);
            parkSpaceService.save(parkSpace);
        }
    }
}
